<template>
  <div>
    <FormPanel ref="topFilterFormPanel" :list="topFilterList" :cols="4" labelWidth="100" :isSubmitBtn="false" @formChange="changeHandle"></FormPanel>

    <FilterTable
      ref="table"
      columnsRef="partPartOutboundPartBreakIndex"
      :columns="columns"
      :params="fetchParams"
      :isPagination="true"
      selectionType="single"
      :dataSource="dataSource"
      :onRowSelectChange="selectTableFun"
      :onColumnsChange="columns => (this.columns = columns)"
      :onSyncTableData="columns => (this.syncColumns = columns)"
    >
      <!-- <template slot="moreActions">
        <span v-show="!invenflag || addFlag" @click="() => deleteHandle()">删除数据</span>
      </template> -->
      <!--:datakey="'records'" :fetchapi="fetchApi" -->
      <template slot="controls">
        <el-button size="small" type="primary" :disabled="beforeAddFlag" @click="beforeAdd">新建</el-button>
        <!-- <el-button size="small" type="primary" :disabled="addFlag" @click="add">新增</el-button> -->
        <AjaxButton size="small" type="primary" :click="save" :disabled="saveFlag">保存</AjaxButton>
        <AjaxButton size="small" type="primary" :click="out" :disabled="outFlag">出库</AjaxButton>
        <AjaxButton size="small" type="primary" :click="cancel" :disabled="cancelFlag">取消</AjaxButton>
        <AjaxButton size="small" type="primary" :click="quit" :disabled="quitFlag">作废</AjaxButton>
        <el-button size="small" type="primary" icon="el-icon-printer" :disabled="printFlag" @click="print">打印</el-button>
      </template>
    </FilterTable>
    <BaseDialog :visible.sync="breakShowFlag" title="报损单选择" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <breakModal :ptype="this.ptype" :type="handleType" :lossNo="topFilterList.find(item => item.fieldName === 'lossNo').initialValue" @close="closeHandler" @change="getLossNo" />
    </BaseDialog>
    <BaseDialog :visible.sync="checkShowFlag" title="盘点单选择" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <checkModal :ptype="this.ptype" :type="handleType" :inventoryNo="topFilterList.find(item => item.fieldName === 'inventoryNo').initialValue" @close="closeHandler" @change="getInventoryNo" />
    </BaseDialog>
    <BaseDialog :visible.sync="editShowFlag" title="配件报损编辑" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <editModal :type="handleType" :formData="formData" @close="closeHandler" @change="getEditPart" />
    </BaseDialog>
    <drawer
      :visible.sync="addShowFlag"
      title="配件报损新增"
      :lossNo="topFilterList.find(item => item.fieldName === 'lossNo').initialValue"
      :width="920"
      destroyOnClose
      :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }"
    >
      <addModal :type="handleType" @close="closeHandler" @change="addPartInfo" />
    </drawer>

    <BaseDialog :visible.sync="checkOutShowFlag" title="提示信息" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <checkOutModal :type="handleType" :checkData="checkData" @close="closeHandler" @change="getOutInfo" />
    </BaseDialog>
    <div v-if="printVehicledShow">
      <BasePrint ref="printVehicled" :data="this.printList" template="templatePartBreak" />
    </div>
  </div>
</template>
<script>
import { searchPartLoss, searchInventoryLoss, cancel, save, quit, out, queryPartSalesIfBear, getAllUser } from '@/api/part/partOutbound/partBreak';
import { dictionary } from '@/utils/dictMixin';
import { getUser, getUserId } from '@/assets/js/auth';
import breakModal from './breakModal';
import checkModal from './checkModal';
import editModal from './editModal';
import addModal from './addModal';
import checkOutModal from './checkOutModal';
import moment from 'moment';
import { debuglog } from 'util';
import { dealerPrintApi } from '@/api/repair/index.js';

export default {
  name: 'partBreakIndex',
  components: {
    breakModal,
    checkModal,
    editModal,
    addModal,
    checkOutModal
  },
  mixins: [dictionary],
  data() {
    return {
      printVehicledShow: false,
      beforeAddFlag: false,
      addFlag: true,
      saveFlag: true,
      outFlag: true,
      cancelFlag: true,
      quitFlag: true,
      printFlag: true,
      topFilterList: this.createTopFilters(),
      fetchParams: {},
      breakShowFlag: false,
      checkShowFlag: false,
      editShowFlag: false,
      addShowFlag: false,
      checkOutShowFlag: false,
      dialogTitle: '',
      columns: this.createTableColumns(),
      handleType: '',
      formData: {},
      checkData: {},
      conf: { add: '新增', editShowFlag: '编辑', checkShowFlag: '显示' },
      dataSource: [],
      syncColumns: [],
      deleteRows: [],
      status: '',
      printList: {},
      selectRow: null,
      printParams: {} // 打印参数
    };
  },
  computed: {
    invenflag() {
      return this.topFilterList.find(item => item.fieldName === 'inventoryNo').initialValue == '';
    },
    ptype() {
      return this.$route.meta.ptype;
    } // 模块区分
  },
  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
    this.initSelect();
    // this.queryPrintParams();
  },
  created() {},
  methods: {
    async initSelect() {
      // 经手人
      let resUser = await getAllUser();
      if (resUser != null) {
        this.topFilterList.find(item => item.fieldName === 'handler').itemList = resUser.data.map(x => ({ value: x.userId, text: x.employeeName }));
      }
    },
    createTopFilters() {
      return [
        {
          type: 'INPUT',
          label: '报损单号',
          fieldName: 'lossNo',
          placeholder: '请输入...',
          unitRender: props => {
            return <el-button icon="el-icon-search" onClick={() => this.selectBreakModal(props)}></el-button>;
          }
        },
        {
          type: 'INPUT',
          label: '盘点单号',
          fieldName: 'inventoryNo',
          placeholder: '请输入...',
          disabled: true,
          unitRender: props => {
            return <el-button icon="el-icon-search" onClick={() => this.selectCheckModal(props)}></el-button>;
          }
        },
        {
          type: 'SELECT',
          label: '经手人',
          fieldName: 'handler',
          itemList: [],
          disabled: true,
          placeholder: '请选择...'
        },
        {
          type: 'DATE',
          label: '报损日期',
          disabled: true,
          fieldName: 'lossDate',
          valueFormat: 'yyyy-MM-dd'
        }
      ];
    },
    createTableColumns() {
      const _this = this;
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          fixed: 'left',
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        // {
        //   title: '操作',
        //   dataIndex: 'column-action',
        //   width: 60,
        //   fixed: 'left',
        //   render: (props, h) => {
        //     return (
        //       <div>
        //         <el-button
        //           size="mini"
        //           disabled={this.topFilterList.find(item => item.fieldName === 'inventoryNo').initialValue === '' && !this.addFlag ? false : true}
        //           type="text"
        //           onClick={() => this.edit(props.row)}
        //         >
        //           编辑
        //         </el-button>
        //       </div>
        //     );
        //   }
        // },
        {
          title: '仓库代码',
          dataIndex: 'STORAGE_CODE',
          sorter: true,
          filter: true,
          hidden: true,
          filterType: 'input'
        },
        {
          title: '仓库',
          dataIndex: 'STORAGE_NAME',
          sorter: true,
          showOverflowTooltip: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '库位',
          dataIndex: 'STORAGE_POSITION_CODE',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '配件代码',
          dataIndex: 'PART_NO',
          sorter: true,
          showOverflowTooltip: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '配件名称',
          dataIndex: 'PART_NAME',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '计量单位',
          dataIndex: 'UNIT_NAME',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '报损数量',
          dataIndex: 'LOSS_QUANTITY',
          sorter: true,
          filter: true,
          precision: 2,
          filterType: 'number'
        },
        // {
        //   title: '含税成本单价',
        //   dataIndex: 'COST_PRICE',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'number',
        //   precision: 2
        // },
        {
          title: '报损单价',
          dataIndex: 'LOSS_PRICE',
          sorter: true,
          filter: true,
          filterType: 'number',
          precision: 2
        },
        // {
        //   title: '含税成本金额',
        //   dataIndex: 'COST_AMOUNT',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'number',
        //   precision: 2
        // },
        {
          title: '报损金额',
          dataIndex: 'LOSS_AMOUNT',
          sorter: true,
          filter: true,
          filterType: 'number',
          precision: 2
        }
      ];
    },
    selectBreakModal() {
      this.breakShowFlag = true;
    },
    selectCheckModal() {
      this.checkShowFlag = true;
    },
    selectTableFun(val) {
      this.selectRow = val;
    },
    beforeAdd() {
      this.status = 'A';
      this.beforeAddFlag = true;
      this.saveFlag = true;
      this.cancelFlag = false;
      this.addFlag = false;
      this.printFlag = true;
      this.topFilterList.find(item => item.fieldName === 'lossNo').disabled = true;
      this.topFilterList.find(item => item.fieldName === 'inventoryNo').disabled = false;
      this.topFilterList.find(item => item.fieldName === 'lossNo').initialValue = '';
      this.topFilterList.find(item => item.fieldName === 'inventoryNo').initialValue = '';
      this.topFilterList.find(item => item.fieldName === 'handler').initialValue = +getUserId();
      this.topFilterList.find(item => item.fieldName === 'lossDate').initialValue = moment().format('YYYY-MM-DD');
      this.topFilterList = [...this.topFilterList];
      this.dataSource = [];
    },
    // deleteHandle() {
    //   this.$confirm('是否确认删除?', '提示', {
    //     confirmButtonText: '确定',
    //     cancelButtonText: '取消',
    //     type: 'warning'
    //   })
    //     .then(async () => {
    //       let rows = this.selectRow[0];
    //       console.log(rows, 'rows');
    //       if (rows.statusitem == 'A') {
    //         rows.statusitem = 'D';
    //         this.deleteRows = [...this.deleteRows, rows];
    //       }
    //       console.log(this.deleteRows, 'deleteRows');
    //       this.BaseTable.EXECUTE_DELETE([rows]);
    //       this.saveFlag = false;
    //       this.outFlag = true;
    //       this.quitFlag = true;
    //     })
    //     .catch(() => {});
    // },
    async save() {
      this.$confirm('是否确认保存?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          this.$refs.topFilterFormPanel.SUBMIT_FORM();
          let total = 0;
          if (this.syncColumns.length <= 0) {
            this.$notify.warning({ title: '提示信息', message: '空配件不能保存!' });
            return;
          }
          this.syncColumns.forEach(x => {
            total += x.COST_AMOUNT;
          });
          let list = [...this.syncColumns, ...this.deleteRows];
          let res = await save({
            ...this.fetchParams,
            partMoveItemTable: list,
            costAmount: total,
            status: this.status,
            ptype: this.ptype ? this.ptype : null
          });
          if (res.resultCode == 200) {
            this.status = 'U';
            this.addFlag = false;
            this.outFlag = false;
            this.cancelFlag = false;
            this.quitFlag = false;
            this.saveFlag = true;
            this.topFilterList.find(item => item.fieldName === 'lossNo').initialValue = res.data.lossNo;
            this.dataSource = [];
            let resss = await searchPartLoss({ lossNo: res.data.lossNo });
            this.BaseTable.EXECUTE_INSERT(resss.data);
            this.$notify.success({ title: '提示信息', message: '报损单保存成功!' });
          } else {
            this.$notify.error({ title: '提示信息', message: '报损单保存失败!' });
          }
          this.deleteRows = [];
        })
        .catch(() => {});
    },
    async out() {
      this.$confirm('是否要出库?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          if (this.dataSource.length == 0) {
            this.$notify.warning({ title: '提示信息', message: '空配件不能出库!' });
            return;
          }
          let lossNo = this.topFilterList.find(item => item.fieldName === 'lossNo').initialValue;
          let inventoryNo = this.topFilterList.find(item => item.fieldName === 'inventoryNo').initialValue;
          // debugger;
          if (lossNo || inventoryNo) {
            let check = await queryPartSalesIfBear({ lossNo: lossNo, inventoryNo: inventoryNo });
            console.log(check, '出库校验');

            // if (check.resultCode == 200 && check.data.total > 0) {
            // this.checkData = check.data.rows;
            // // this.checkOutShowFlag = true;
            // } else {
            let res = await out({ lossNo: lossNo, inventoryNo: inventoryNo });
            if (res.resultCode == 200) {
              this.beforeAddFlag = false;
              this.cancelFlag = false;
              this.printFlag = false;
              this.outFlag = true;
              this.addFlag = true;
              this.quitFlag = true;
              this.saveFlag = true;
              return this.$notify.success({ title: '提示信息', message: '报损单出库成功!' });
            } else {
              return this.$notify.error({ title: '提示信息', message: '报损单出库失败!' });
            }
            // }
          }
        })
        .catch(() => {});
    },
    async cancel() {
      const lossNo = this.topFilterList.find(item => item.fieldName === 'lossNo').initialValue;
      const inventoryNo = this.topFilterList.find(item => item.fieldName === 'inventoryNo').initialValue;
      if (lossNo || inventoryNo) {
        let res = await cancel({ lossNo: lossNo, inventoryNo: inventoryNo });
      }
      this.beforeAddFlag = false;
      this.addFlag = true;
      this.saveFlag = true;
      this.cancelFlag = true;
      this.outFlag = true;
      this.quitFlag = true;
      this.printFlag = true;
      this.topFilterList.find(item => item.fieldName === 'lossNo').disabled = false;
      this.topFilterList.find(item => item.fieldName === 'inventoryNo').disabled = true;
      this.topFilterList.find(item => item.fieldName === 'lossNo').initialValue = '';
      this.topFilterList.find(item => item.fieldName === 'inventoryNo').initialValue = '';
      this.topFilterList.find(item => item.fieldName === 'handler').initialValue = '';
      this.topFilterList.find(item => item.fieldName === 'lossDate').initialValue = '';
      this.dataSource = [];
      this.deleteRows = [];
    },
    async quit() {
      this.$confirm('您确定要作废该单据吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const lossNo = this.topFilterList.find(item => item.fieldName === 'lossNo').initialValue;
          if (lossNo) {
            let res = await quit({ lossNo: lossNo });
            if (res.resultCode == 200) {
              this.topFilterList.find(item => item.fieldName === 'lossNo').disabled = false;
              this.topFilterList.find(item => item.fieldName === 'lossNo').initialValue = '';
              this.topFilterList.find(item => item.fieldName === 'handler').initialValue = '';
              this.topFilterList.find(item => item.fieldName === 'inventoryNo').initialValue = '';
              this.topFilterList.find(item => item.fieldName === 'lossDate').initialValue = '';
              this.beforeAddFlag = false;
              this.addFlag = true;
              this.outFlag = true;
              this.cancelFlag = true;
              this.quitFlag = true;
              this.saveFlag = true;
              this.dataSource = [];
              return this.$notify.success({ title: '提示信息', message: '报损单作废成功!' });
            } else {
              return this.$notify.error({ title: '提示信息', message: '报损单作废失败!' });
            }
          }
        })
        .catch(() => {});
    },
    async print() {
      this.printVehicledShow = true;
      let userData = await getAllUser();
      let handlerName = '';

      for (var i = 0; i < userData.data.length; i++) {
        if (userData.data[i].userId == this.topFilterList.find(item => item.fieldName === 'handler').initialValue) {
          handlerName = userData.data[i].employeeName;
          break;
        }
      }
      let userName = userData.data.find(x => x.userId == getUserId()).employeeName;
      if (1 == 1) {
        this.printList = {
          lossNo: this.topFilterList.find(item => item.fieldName === 'lossNo').initialValue,
          handler: handlerName,
          lossDate: this.topFilterList.find(item => item.fieldName === 'lossDate').initialValue,
          items: [...this.syncColumns],
          USER_NAME: userName
        };
        this.printList.lossDate = moment(this.printList.lossDate).format('YYYY-MM-DD');
        console.log(this.printList, 'this.printList');
        this.$nextTick(() => {
          this.$refs.printVehicled.EXCUTE_PRINT();
        });
      }
    },
    add() {
      // this.outFlag = true;
      // this.quitFlag = true;
      this.addShowFlag = true;
    },
    edit(row) {
      this.formData = row;
      this.editShowFlag = true;
    },
    changeHandle(val) {
      this.fetchParams = Object.assign({}, val);
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    closeHandler(val, type) {
      this.breakShowFlag = val;
      this.checkShowFlag = val;
      this.addShowFlag = val;
      this.editShowFlag = val;
      this.checkOutShowFlag = val;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    },
    async getLossNo(val) {
      this.breakShowFlag = false;
      let res = await searchPartLoss({ lossNo: val[0].LOSS_NO, ptype: this.ptype });
      if ((res.resultCode = 200)) {
        if (res.data && res.data.length) {
          this.status = 'U';
          // let lockUser = res.data[0].LOCK_USER;
          // if (lockUser && lockUser === '') {
          //   return this.$notify.error({ title: '提示信息', message: '已被其他用户锁定!' });
          // }
          this.BaseTable.EXECUTE_INSERT(res.data);
        }
      }
      this.topFilterList.find(item => item.fieldName === 'lossNo').disabled = true;
      this.topFilterList.find(item => item.fieldName === 'lossNo').initialValue = val[0].LOSS_NO;
      this.topFilterList.find(item => item.fieldName === 'inventoryNo').initialValue = val[0].INVENTORY_NO;
      this.topFilterList.find(item => item.fieldName === 'handler').initialValue = +val[0].HANDLER;
      this.topFilterList.find(item => item.fieldName === 'lossDate').initialValue = val[0].LOSS_DATE;
      if (this.topFilterList.find(item => item.fieldName === 'inventoryNo').initialValue === '') {
        this.addFlag = false;
      } else {
        this.addFlag = true;
      }
      this.beforeAddFlag = true;
      this.outFlag = false;
      this.cancelFlag = false;
      this.quitFlag = false;
      this.topFilterList = [...this.topFilterList];
      // this.BaseTable.EXECUTE_INSERT(res.data);
    },
    async getInventoryNo(val) {
      // debugger;
      let res = await searchInventoryLoss({ inventoryNo: val[0].INVENTORY_NO });
      let userId = this.topFilterList.find(item => item.fieldName === 'handler').initialValue;
      // let lockUser = val[0].LOCK_USER;
      // if (lockUser != null && lockUser != '' && userId != lockUser) {
      //   return;
      // }
      this.addFlag = true;
      this.checkShowFlag = false;
      this.topFilterList.find(item => item.fieldName === 'lossNo').disabled = true;
      this.topFilterList.find(item => item.fieldName === 'inventoryNo').disabled = true;
      this.topFilterList.find(item => item.fieldName === 'inventoryNo').initialValue = val[0].INVENTORY_NO;
      this.topFilterList = [...this.topFilterList];
      this.BaseTable.EXECUTE_INSERT(res.data);
      this.saveFlag = false;
    },
    addPartInfo(val) {
      let pageData = [...this.syncColumns];
      console.log(pageData, 'table数据');
      if (val.PART_NO != '' && val.STORAGE_CODE != '') {
        if (pageData.length > 0) {
          for (const item of pageData) {
            if (item.PART_NO == val.PART_NO && item.STORAGE_CODE == val.STORAGE_CODE) {
              return this.$notify.error({ title: '提示信息', message: '信息已存在，不允许重复添加!' });
            }
          }
        }
        this.BaseTable.EXECUTE_INSERT(val);
        this.topFilterList.find(item => item.fieldName === 'inventoryNo').disabled = true;
        this.saveFlag = false;
        this.outFlag = true;
        this.quitFlag = true;
      }
    },
    getEditPart(val) {
      console.log(val, '配件编辑');
      console.log(this.syncColumns, '配件匹配');
      this.syncColumns.forEach(x => {
        console.log(x, '配件x');
        // debugger;
        if (x.PART_NO == val.PART_NO && x.STORAGE_CODE == val.STORAGE_CODE) {
          if (x.LOSS_QUANTITY != val.LOSS_QUANTITY || x.PART_NAME != val.PART_NAME) {
            x.LOSS_QUANTITY = val.LOSS_QUANTITY;
            x.PART_NAME = val.PART_NAME;
            x.LOSS_AMOUNT = val.LOSS_AMOUNT;
            x.COST_AMOUNT = val.LOSS_AMOUNT;
            this.saveFlag = false;
            this.cancelFlag = false;
            this.editShowFlag = false;
            this.quitFlag = true;
            this.outFlag = true;
          }
        }
      });
    },
    async getOutInfo(val) {
      // debugger;
      this.checkOutShowFlag = false;
      let lossNo = this.topFilterList.find(item => item.fieldName === 'lossNo').initialValue;
      let inventoryNo = this.topFilterList.find(item => item.fieldName === 'inventoryNo').initialValue;
      let res = await out({ lossNo: lossNo, inventoryNo: inventoryNo });
      if (res.resultCode == 200) {
        this.beforeAddFlag = false;
        this.outFlag = true;
        this.printFlag = false;
        this.addFlag = true;
        this.quitFlag = true;
        return this.$notify.success({ title: '提示信息', message: '报损单出库成功!' });
      } else {
        return this.$notify.success({ title: '提示信息', message: '报损单出库失败!' });
      }
    },
    // 查询打印参数
    async queryPrintParams() {
      let res = await dealerPrintApi({
        vModule: '90211009',
        vNormalCode: 'BJBS'
      });
      if (res.resultCode == 200 && res.data.length) {
        this.printParams = res.data[0];
      }
      console.log(this.printParams, '打印参数');
    }
  }
};
</script>

<style lang="less" scoped></style>
